<?php

namespace app\index\traits;

use ShidianUtil\Utils\CheckUtil;
use ShidianUtil\Utils\RandUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use think\Request;

/**
 * Trait TempTokenCheckTrait
 * @package app\index\traits
 */
trait TempTokenCheckTrait
{
    use SessionMemberDraftTrait;
    use CaptchaTrait;

    /**
     * 获取和验证登录信息（手机号，邀请码）
     * @param Request $request
     * @return array
     */
    private function getLoginInfo(Request $request)
    {

        $tempToken = $request->param('tempToken');

        if (not_blank($tempToken)) {

            $tempSession = $this->decodeTempToken($tempToken);
            if (is_null($tempSession)) {
                throw new ValidateException('找不到该临时会话');
            }

            $phone = $tempSession['phone'] ?? null;
            $inviteCode = $tempSession['inviteCode'] ?? null;
        } else {
            $phone = $request->param('phone');
            $inviteCode = $request->param('inviteCode');

            //先验证认证资料
            $this->checkMemberDraft($request->param('memberDraft'));

            // 验证短信验证码
            $this->checkCaptcha(CAPTCHA_DENGLU, $phone, $request->param('captcha'));
        }

        if (is_blank($phone)) {
            throw new ValidateException('请输入手机号码');
        }

        if (!CheckUtil::isPhoneNumber($phone)) {
            throw new ValidateException('请输入正确的手机号码');
        }

        return [
            'phone' => $phone,
            'inviteCode' => $inviteCode,
        ];
    }

    /**
     * 获取tempToken缓存
     * @param $tempToken
     * @return array|null
     */
    private function decodeTempToken($tempToken): ?array
    {
        $key = 'temp_token:' . $tempToken;
        return Cache::get($key, null);
    }

    /**
     * 缓存tempToken
     * @param $phone
     * @param $inviteCode
     * @return string
     */
    private function encodeTempToken($phone, $inviteCode)
    {

        // 临时token
        $tempToken = RandUtil::uuid(32);

        $key = 'temp_token:' . $tempToken;

        $data = [
            'phone' => $phone,
            'inviteCode' => $inviteCode,
        ];

        Cache::set($key, $data, 86400);

        return $tempToken;
    }

}